import requests  

class GrafanaAlert:
    def __init__(self, grafana_host_url, token) -> None:
        self.grafana_host_url = grafana_host_url
        self.token = token

    def response_print(self, response):
        # 检查请求是否成功  
        if response.status_code in [200, 201]:
            print('请求成功:', response.json())
            return response.json()
        elif response.status_code == 204:
            return True
        else:  
            print(f'请求失败: {response.status_code} - {response.text}')
            return False
    
    def get_alert_rules(self):
        """
        获取告警规则
        """

        headers = {  
            'Authorization': f'Bearer {self.token}',  
        }  

        grafana_sub_url = "/api/v1/provisioning/alert-rules"

        grafana_url = self.grafana_host_url + grafana_sub_url

        response = requests.get(grafana_url, headers=headers)

        # 检查请求是否成功  
        response_json = self.response_print(response)

        return response_json

    def create_alert_rules(self, rules_info_dict, folderUID, datasourceUid):
        """
            创建告警规则
        """

        # 请求头，包含 Authorization  
        headers = {  
            'Authorization': f'Bearer {self.token}',  
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }  

        data = {
          "uid": "",
          "ruleGroup": "API",
          "title": rules_info_dict["title"],
          "folderUID": folderUID,   # 文件uid们需要查询
          "condition": "C",
          "data": [
            {
              "refId": "A",
              "relativeTimeRange": {
                "from": 600,
                "to": 0
              },
              "datasourceUid": datasourceUid,    # 数据源uid需要查询
              "model": {
                "editorMode": "code",
                "expr": rules_info_dict["name"],
                "instant": True,
                "intervalMs": 1000,
                "legendFormat": "__auto",
                "maxDataPoints": 43200,
                "range": False,
                "refId": "A"
              }
            },
            {
              "refId": "C",
              "relativeTimeRange": {
                "from": 600,
                "to": 0
              },
              "datasourceUid": "__expr__",
              "model": {
                "conditions": [
                  {
                    "evaluator": {
                      "params": [
                        1,
                        1
                      ],
                      "type": "outside_range"
                    },
                    "operator": {
                      "type": "and"
                    },
                    "query": {
                      "params": [
                        "C"
                      ]
                    },
                    "reducer": {
                      "params": [],
                      "type": "last"
                    },
                    "type": "query"
                  }
                ],
                "datasource": {
                  "type": "__expr__",
                  "uid": "__expr__"
                },
                "expression": "A",
                "intervalMs": 1000,
                "maxDataPoints": 43200,
                "refId": "C",
                "type": "threshold"
              }
            }
          ],
          "noDataState": "Alerting",
          "execErrState": "Alerting",
          "for": rules_info_dict["for"],
          "annotations": {
            "description": "在指定时间内无正常信息返回",
            "runbook_url": "",
            "summary": rules_info_dict["summary"]
          },
          "labels": {
            "name": "sumz-port"
          },
          "isPaused": False,
          "notification_settings": {
            "receiver": "西南"
          }
        }

        grafana_sub_url = "/api/v1/provisioning/alert-rules"

        grafana_url = self.grafana_host_url + grafana_sub_url

        # 使用requests库发送POST请求  
        response = requests.post(grafana_url, json=data, headers=headers)  

        # 检查请求是否成功  
        self.response_print(response)
        # 请求成功: {'id': 3, 'uid': 'cdu3j3mj7qrcwb', 'orgID': 1, 'folderUID': 'cdu2geontnke8a', 'ruleGroup': 'API', 'title': '鍩庡競灏忔椂鏁版嵁', 'condition': 'B', 'data': [{'refId': 'A', 'queryType': '', 'relativeTimeRange': {'from': 600, 'to': 0}, 'datasourceUid': 'adtaok5che4n4b', 'model': {'expr': 'monitor_city_hour2', 'hide': False, 'intervalMs': 1000, 'maxDataPoints': 43200, 'refId': 'A'}}, {'refId': 'B', 'queryType': '', 'relativeTimeRange': {'from': 600, 'to': 0}, 'datasourceUid': '-100', 'model': {'conditions': [{'evaluator': {'params': [1, 1], 'type': 'outside_range'}, 'operator': {'type': 'and'}, 'query': {'params': ['A']}, 'reducer': {'params': [], 'type': 'last'}, 'type': 'query'}], 'datasource': {'type': '__expr__', 'uid': '-100'}, 'hide': False, 'intervalMs': 1000, 'maxDataPoints': 43200, 'refId': 'B', 'type': 'classic_conditions'}}], 'updated': '2024-08-07T18:05:21.172068361+08:00', 'noDataState': 'OK', 'execErrState': 'OK', 'for': '10m', 'annotations': {'summary': '鎺ュ彛寮傚父'}, 'labels': {'API': 'sumz-port'}, 'provenance': 'api', 'isPaused': False, 'notification_settings': None, 'record': None}
        
        return True
    

    def delete_alert_rules(self, uid):
        """
            删除告警规则
        """

        headers = {  
            'Authorization': f'Bearer {self.token}',  
        }  

        grafana_sub_url = "/api/v1/provisioning/alert-rules/" + uid

        grafana_url = self.grafana_host_url + grafana_sub_url

        response = requests.delete(grafana_url, headers=headers)

        # 检查请求是否成功  
        self.response_print(response)
        # 204请求成功:  -

        return True